<template>
  <div class="wallet-container">
    <div class="wallet-header">
      <el-page-header @back="goBack" title="我的钱包" />
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%" :rows="6" animated />
    </div>
    
    <template v-else>
      <!-- 余额卡片 -->
      <el-card class="balance-card">
        <div class="balance-info">
          <div class="balance-icon">💰</div>
          <div class="balance-details">
            <div class="balance-label">当前余额</div>
            <div class="balance-amount">¥{{ currentBalance.toFixed(2) }}</div>
          </div>
          <el-button type="primary" @click="showRechargeDialog = true">立即充值</el-button>
        </div>
      </el-card>
    
      <!-- 快捷充值 -->
      <el-card class="quick-recharge-card">
        <template #header>
          <span>快捷充值</span>
        </template>
        
        <div class="quick-amounts">
          <div 
            v-for="amount in quickAmounts" 
            :key="amount"
            class="quick-amount-item"
            @click="quickRecharge(amount)"
          >
            <div class="amount-value">¥{{ amount }}</div>
          </div>
        </div>
      </el-card>
      
      <!-- 充值说明 -->
      <el-card class="info-card">
        <template #header>
          <span>充值说明</span>
        </template>
        
        <div class="recharge-info">
          <p>• 充值金额实时到账，可用于订单支付</p>
          <p>• 单次充值金额范围：1-10000元</p>
          <p>• 支持多种支付方式：支付宝、微信支付</p>
          <p>• 余额不支持提现，请合理充值</p>
        </div>
      </el-card>
    </template>
    
    <!-- 充值对话框 -->
    <el-dialog v-model="showRechargeDialog" title="余额充值" width="400px" :close-on-click-modal="false">
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="80px">
        <el-form-item label="充值金额" prop="amount">
          <el-input 
            v-model="rechargeForm.amount"
            placeholder="请输入充值金额"
            type="number"
            :min="1"
            :max="10000"
          >
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-radio-group v-model="rechargeForm.paymentMethod">
            <el-radio label="alipay">
              <img src="http://47.122.155.110/assets/payment/alipay.png" alt="支付宝" class="payment-icon">
              支付宝
            </el-radio>
            <el-radio label="wechat">
              <img src="http://47.122.155.110/assets/payment/wechat.png" alt="微信支付" class="payment-icon">
              微信支付
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRechargeDialog = false">取消</el-button>
          <el-button type="primary" :loading="recharging" @click="submitRecharge">
            确认充值
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 充值结果对话框 -->
    <el-dialog v-model="rechargeResultVisible" :title="rechargeSuccess ? '充值成功' : '充值失败'" width="300px">
      <div class="recharge-result">
        <div class="result-icon">
          <el-icon v-if="rechargeSuccess" class="success-icon" size="60">
            <CircleCheckFilled />
          </el-icon>
          <el-icon v-else class="error-icon" size="60">
            <CircleCloseFilled />
          </el-icon>
        </div>
        <div class="result-message">
          {{ rechargeSuccess ? `充值成功，当前余额：¥${currentBalance.toFixed(2)}` : '充值失败，请重试' }}
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeRechargeResult">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'

interface RechargeForm {
  amount: string
  paymentMethod: string
}

const router = useRouter()
const loading = ref(true)
const recharging = ref(false)
const showRechargeDialog = ref(false)
const rechargeResultVisible = ref(false)
const rechargeSuccess = ref(false)
const currentBalance = ref(0)

// 快捷充值金额
const quickAmounts = [50, 100, 200, 500, 1000]

// 充值表单
const rechargeForm = ref<RechargeForm>({
  amount: '',
  paymentMethod: 'alipay'
})

const rechargeFormRef = ref()

// 表单验证规则
const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        const amount = parseFloat(value)
        if (isNaN(amount) || amount <= 0) {
          callback(new Error('充值金额必须大于0'))
        } else if (amount > 10000) {
          callback(new Error('单次充值金额不能超过10000元'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取当前余额
const fetchBalance = async () => {
  try {
    const response = await axios.get('/api/user/wallet/balance')
    currentBalance.value = parseFloat(response.data.balance)
  } catch (error) {
    console.error('获取余额失败:', error)
    ElMessage.error('获取余额失败，请稍后重试')
    currentBalance.value = 0
  }
}

// 快捷充值
const quickRecharge = (amount: number) => {
  rechargeForm.value.amount = amount.toString()
  showRechargeDialog.value = true
}

// 提交充值
const submitRecharge = async () => {
  if (!rechargeFormRef.value) return
  
  await rechargeFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    try {
      recharging.value = true
      
      // 模拟支付处理时间
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      const response = await axios.post('/api/user/wallet/recharge', {
        amount: parseFloat(rechargeForm.value.amount)
      })
      
      if (response.data.success) {
        rechargeSuccess.value = true
        currentBalance.value = parseFloat(response.data.newBalance)
        ElMessage.success('充值成功')
  } else {
        rechargeSuccess.value = false
        ElMessage.error(response.data.message || '充值失败')
      }
      
    } catch (error) {
      console.error('充值失败:', error)
      rechargeSuccess.value = false
      
      if (axios.isAxiosError(error) && error.response) {
        const errorMessage = error.response.data?.message || '充值失败'
        ElMessage.error(errorMessage)
      } else {
        ElMessage.error('充值失败，请稍后重试')
      }
      
    } finally {
      recharging.value = false
      showRechargeDialog.value = false
      rechargeResultVisible.value = true
    }
  })
}

// 关闭充值结果对话框
const closeRechargeResult = () => {
  rechargeResultVisible.value = false
    
  // 重置表单
  rechargeForm.value = {
    amount: '',
    paymentMethod: 'alipay'
  }
  
  if (rechargeFormRef.value) {
    rechargeFormRef.value.resetFields()
  }
}

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    await fetchBalance()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.wallet-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.wallet-header {
  margin-bottom: 20px;
}

.loading-container {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
}

.balance-card, .quick-recharge-card, .info-card {
  margin-bottom: 20px;
}

.balance-info {
  display: flex;
  align-items: center;
  padding: 20px;
}

.balance-icon {
  font-size: 48px;
  margin-right: 20px;
}

.balance-details {
  flex: 1;
}

.balance-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.balance-amount {
  font-size: 32px;
  font-weight: bold;
  color: #f56c6c;
}

.quick-amounts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 15px;
  padding: 10px 0;
}

.quick-amount-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: white;
}

.quick-amount-item:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.amount-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.recharge-info {
  line-height: 1.8;
  color: #666;
}

.recharge-info p {
  margin: 8px 0;
}

.payment-icon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  vertical-align: middle;
}

.recharge-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.result-icon {
  margin-bottom: 20px;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.result-message {
  font-size: 16px;
  text-align: center;
}

@media (max-width: 768px) {
  .wallet-container {
    padding: 10px;
}

  .balance-info {
    flex-direction: column;
    text-align: center;
  gap: 15px;
}

  .balance-icon {
    margin-right: 0;
}

  .quick-amounts {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>